﻿ 
using BeIT.MemCached;
using System.Web.UI;
using System;

namespace MemcachedViewStatePageAdapter
{
	class MemcachedPageStatePersister : HiddenFieldPageStatePersister 
	{
		internal MemcachedPageStatePersister(Page page)
			: base(page)
		{

		}
		const string CacheName = "ViewStateCache";
		public override void Load()
		{
			base.Load();
			if (this.ControlState != null)
			{
				Pair pair = this.ControlState as Pair;
				Pair states = MemcachedClient.GetInstance(CacheName).Get(pair.Second as string) as Pair;
				this.ViewState = states.First;
				this.ControlState = states.Second;
			}
		}

		public override void Save()
		{
			if (this.ControlState != null)
			{
				string id = Guid.NewGuid().ToString();
				MemcachedClient.GetInstance(CacheName).Set(id, new Pair(this.ViewState, this.ControlState), TimeSpan.FromDays(2));
				this.ControlState = new Pair("key", id);
				this.ViewState = null;
			}
			base.Save();
		}
	}
}

